<template>
  <div class="user-center-container animate__animated animate__fadeIn">
    <!-- 上部分：用户信息 -->
    <div class="user-profile-section">
      <div class="user-avatar">
        <img :src="userInfo.profilePicture || defaultAvatar" alt="用户头像" @click="handleAvatarClick" :class="{ 'clickable': isCurrentUser }">
        <input 
          type="file" 
          ref="avatarInput" 
          style="display: none" 
          accept="image/*" 
          @change="handleAvatarChange"
        />
      </div>
      <div class="user-info">
        <div class="username-container">
          <h2 class="username">{{ userInfo.username }}</h2>
          <button v-if="isCurrentUser" class="edit-btn" @click="handleEdit">
            <t-icon name="edit" />
            编辑资料
          </button>
          <button 
            v-if="!isCurrentUser && profile.id" 
            class="follow-btn" 
            :class="{ 'following': isFollowing }"
            @click="handleFollowToggle"
          >
            <t-icon :name="isFollowing ? 'minus' : 'plus'" />
            {{ isFollowing ? '已关注' : '关注' }}
          </button>
        </div>
        <p class="description">{{ userInfo.description || '这个人很懒，什么都没有留下...' }}</p>
        
        <div class="user-details">
          <div class="detail-item" v-if="userInfo.fullName">
            <span class="detail-label">姓名:</span>
            <span class="detail-value">{{ userInfo.fullName }}</span>
          </div>
          <div class="detail-item" v-if="userInfo.email">
            <span class="detail-label">邮箱:</span>
            <span class="detail-value">{{ userInfo.email }}</span>
          </div>
          <div class="detail-item" v-if="userInfo.gender">
            <span class="detail-label">性别:</span>
            <span class="detail-value">{{ formatGender(userInfo.gender) }}</span>
          </div>
          <div class="detail-item" v-if="userInfo.phoneNumber">
            <span class="detail-label">手机号码:</span>
            <span class="detail-value">{{ userInfo.phoneNumber }}</span>
          </div>
          <div class="detail-item" v-if="userInfo.address">
            <span class="detail-label">地址:</span>
            <span class="detail-value">{{ userInfo.address }}</span>
          </div>
          <div class="detail-item" v-if="userInfo.dateOfBirth">
            <span class="detail-label">出生日期:</span>
            <span class="detail-value">{{ formatDate(userInfo.dateOfBirth) }}</span>
          </div>
        </div>
        
        <div class="user-stats">
          <div class="stat-item">
            <span class="stat-value">{{ userInfo.articleCount || 0 }}</span>
            <span class="stat-label">文章</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ userInfo.likeCount || 0 }}</span>
            <span class="stat-label">获赞</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ userInfo.followerCount || 0 }}</span>
            <span class="stat-label">粉丝</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ userInfo.followingCount || 0 }}</span>
            <span class="stat-label">关注</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 下部分：内容导航 -->
    <div class="content-navigation">
      <div class="nav-tabs">
        <router-link 
          :to="{name: 'userLike', params: {id: userInfo.id}}"
          class="nav-tab"
          :class="{ 'active': $route.name === 'userLike' }"
        >
          <span>点赞</span>
        </router-link>
        <router-link 
          :to="{name: 'userArticle', params: {id: userInfo.id}}"
          class="nav-tab"
          :class="{ 'active': $route.name === 'userArticle' }"
        >
          <span>文章</span>
        </router-link>
        <router-link 
          :to="{name: 'userQuestion', params: {id: userInfo.id}}"
          class="nav-tab"
          :class="{ 'active': $route.name === 'userQuestion' }"
        >
          <span>提问</span>
        </router-link>
        <router-link 
          :to="{name: 'userAnswer', params: {id: userInfo.id}}"
          class="nav-tab"
          :class="{ 'active': $route.name === 'userAnswer' }"
        >
          <span>回答</span>
        </router-link>
        <router-link 
          :to="{name: 'userFavorite', params: {id: userInfo.id}}"
          class="nav-tab"
          :class="{ 'active': $route.name === 'userFavorite' }"
        >
          <span>收藏夹</span>
        </router-link>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <router-view></router-view>
    </div>
    
    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人资料"
      width="500px"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="个人描述">
          <el-input 
            v-model="editForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="介绍一下自己吧"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editForm.fullName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="editForm.gender" placeholder="请选择性别">
            <el-option label="男" value="male"></el-option>
            <el-option label="女" value="female"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editForm.phoneNumber" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="editForm.dateOfBirth"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { storeToRefs } from 'pinia'
import { findUserById, updateUser, uploadAvatar, followUser, unfollowUser, isFollowing as isFollowingApi } from '@/api/userApi'
import defaultAvatar from '@/imgs/avatar.png'
import { ElMessage } from 'element-plus'
import 'animate.css'

const route = useRoute()
const router = useRouter()

// 获取 userStore 实例
const userStore = useUserStore()
const { profile } = storeToRefs(userStore)

const userInfo = ref({})
const isCurrentUser = computed(() => profile.value.id === Number(route.params.id))
const editDialogVisible = ref(false)
const isFollowing = ref(false)
const editForm = ref({
  id: null,
  description: '',
  email: '',
  fullName: '',
  gender: '',
  phoneNumber: '',
  address: '',
  dateOfBirth: ''
})
const avatarInput = ref(null)

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString();
}

// 格式化性别
const formatGender = (gender) => {
  if (gender === 'male') return '男';
  if (gender === 'female') return '女';
  return '其他';
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await findUserById(route.params.id)
    if (response.code == 200) {
      userInfo.value = response.data
      // 如果不是当前用户，检查是否已关注
      if (!isCurrentUser.value && profile.value.id) {
        checkIfFollowing()
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 检查是否已关注该用户
const checkIfFollowing = async () => {
  try {
    const response = await isFollowingApi(profile.value.id, userInfo.value.id)
    if (response.code == 200) {
      isFollowing.value = response.data
    }
  } catch (error) {
    console.error('检查关注状态失败:', error)
  }
}

// 处理关注/取消关注
const handleFollowToggle = async () => {
  if (!profile.value.id) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    if (isFollowing.value) {
      // 取消关注
      const response = await unfollowUser({
        followerId: profile.value.id,
        followingId: userInfo.value.id
      })
      if (response.code == 200) {
        isFollowing.value = false
        userInfo.value.followerCount = Math.max(0, (userInfo.value.followerCount || 0) - 1)
        ElMessage.success('已取消关注')
      }
    } else {
      // 关注用户
      const response = await followUser({
        followerId: profile.value.id,
        followingId: userInfo.value.id
      })
      if (response.code == 200) {
        isFollowing.value = true
        userInfo.value.followerCount = (userInfo.value.followerCount || 0) + 1
        ElMessage.success('关注成功')
      }
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 更新 store 中的用户信息
const updateUserStore = () => {
  userStore.getProfile()
}

onMounted(fetchUserInfo)

// 监听路由变化，重新获取用户信息
watch(() => route.params.id, (newId, oldId) => {
  if (newId !== oldId) {
    fetchUserInfo()
  }
})

// 打开编辑对话框
const handleEdit = () => {
  editForm.value = {
    id: userInfo.value.id,
    description: userInfo.value.description || '',
    email: userInfo.value.email || '',
    fullName: userInfo.value.fullName || '',
    gender: userInfo.value.gender || 'other',
    phoneNumber: userInfo.value.phoneNumber || '',
    address: userInfo.value.address || '',
    dateOfBirth: userInfo.value.dateOfBirth || ''
  }
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    const response = await updateUser(editForm.value)
    if (response.code == 200) {
      ElMessage({
        message: '资料更新成功',
        type: 'success'
      })
      editDialogVisible.value = false
      // 重新获取用户信息
      await fetchUserInfo()
      // 更新 store 中的用户信息
      updateUserStore()
    } else {
      ElMessage.error('资料更新失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('资料更新失败')
  }
}

// 处理头像点击
const handleAvatarClick = () => {
  if (isCurrentUser.value) {
    avatarInput.value.click()
  }
}

// 处理头像变更
const handleAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  try {
    const response = await uploadAvatar(userInfo.value.id, file)
    if (response.code == 200) {
      ElMessage({
        message: '头像更新成功',
        type: 'success'
      })
      // 重新获取用户信息
      await fetchUserInfo()
      // 更新 store 中的用户信息
      updateUserStore()
    } else {
      ElMessage.error('头像更新失败')
    }
  } catch (error) {
    console.error('更新头像失败:', error)
    ElMessage.error('头像更新失败')
  }
  
  // 清空文件输入，以便于下次选择同一文件时也能触发 change 事件
  event.target.value = ''
}
</script>

<style scoped>
.user-center-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
}

.user-profile-section {
  display: flex;
  padding: 30px;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.user-avatar {
  width: 120px;
  height: 120px;
  margin-right: 30px;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f0f2f5;
}

.user-avatar img.clickable {
  cursor: pointer;
  transition: all 0.3s;
}

.user-avatar img.clickable:hover {
  border-color: #409EFF;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

.user-info {
  flex: 1;
}

.username-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.username {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.edit-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn:hover {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.follow-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: 500;
  font-size: 14px;
  background: #409EFF;
  color: white;
  border: 1px solid #409EFF;
  cursor: pointer;
  transition: all 0.3s;
}

.follow-btn:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

.follow-btn.following {
  background: #f4f4f5;
  color: #909399;
  border-color: #dcdfe6;
}

.follow-btn.following:hover {
  background: #f0f0f0;
  color: #606266;
}

.description {
  color: #606266;
  margin-bottom: 15px;
  font-size: 14px;
}

.user-details {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
}

.detail-value {
  color: #303133;
}

.user-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.content-navigation {
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.nav-tabs {
  display: flex;
  border-bottom: 1px solid #e4e7ed;
}

.nav-tab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 15px 25px;
  color: #606266;
  text-decoration: none;
  transition: all 0.3s ease;
  border-bottom: 3px solid transparent;
}

.nav-tab:hover {
  color: #409EFF;
}

.nav-tab.active {
  color: #409EFF;
  border-bottom: 3px solid #409EFF;
}

.content-area {
  flex: 1;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

@media (max-width: 768px) {
  .user-profile-section {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .user-avatar {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .user-details {
    grid-template-columns: 1fr;
  }
  
  .detail-item {
    justify-content: center;
  }
  
  .user-stats {
    justify-content: center;
  }
  
  .nav-tabs {
    overflow-x: auto;
  }
  
  .nav-tab {
    padding: 10px 15px;
    white-space: nowrap;
  }
}
</style>
